/* James McTaggart (jcm28) Informatics
Multimedia Communications Technology - 17th May 2007
In making this submission I declare that my work contains no examples
of misconduct, such as plagiarism, collusion, or fabrication of results.
*/

package client;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Timer;
import java.util.TimerTask;

public class ClientBleepThread extends Thread {

	private DatagramSocket socket;
	private Client client;
	private byte[] inData = new byte[60];
	private DatagramPacket inPacket;
	private int delay;
	private Timer timer;
	
	public ClientBleepThread(Client client, DatagramSocket socket, int delay) {
		this.socket = socket;
		this.client = client;
		this.delay = delay;
		inPacket = new DatagramPacket(inData,inData.length);
		timer = new Timer();
	}
	
	@Override
	public void run() {
		inData = new byte[60];
		while(true){
			try{
				socket.receive(inPacket);
				int n = getMessageID(new String(inPacket.getData()));
				if(n==202){
					timer.schedule(new BleepTimerTask(client,true), delay-1000);
					//client.setBleep(true);
				}
				else if(n==203){
					timer.schedule(new BleepTimerTask(client,false), delay);
					//client.setBleep(false);
				}
			}
			catch(Exception e){}
		}
	}
	private int getMessageID(String message) {
		try {
			int id = Integer.parseInt(message.substring(0, 3));
			if (id != 202 && id != 203) {
				return -1;
			}
			return id;
		} catch (NumberFormatException e) {
			return -1;
		}
	}
	
	public class BleepTimerTask extends TimerTask{
		private Client client;
		private boolean bleepValue;
		public BleepTimerTask(Client client, boolean bleepValue){
			this.client = client;
			this.bleepValue = bleepValue;
		}
		
		public void run() {
			client.setBleep(bleepValue);
		}
	}
		
}
